import React from "react";
import {HeaderLeft,HeaderRight} from './components/View_HeaderBtn';
import {hashHistory} from 'react-router';

import Relay from "react-relay";

import TableDetail from './components/View_TableDetail';  //表格detail

import {message} from 'antd';

import "./rebatemanage.css";

import EnterpriseTaxRebateList from './mutation/enterpriseTaxRebateList';
import OperModal from './components/Page_OperModal';

export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            sendStatus:"1",  //寄送状态  默认为待寄送
            data:[],
            searchValue:"",   //搜索框value
            curPageNum:[1,1]  // 寄送状态的当前页码
        };

        this.handleHeaSearch = this.handleHeaSearch.bind(this);
        this.handleBtn1Click = this.handleBtn1Click.bind(this);
        this.handleSearchChange = this.handleSearchChange.bind(this);
        this.paginationChange = this.paginationChange.bind(this);
    }

    componentWillMount(){
    }

    componentDidMount(){
        // 更新数据 (更新页码的数据)
        this.requestInfo("",this.state.curPageNum[this.state.sendStatus-1],10,this.state.sendStatus);
    }

    // 搜索
    handleHeaSearch(value){
        if(value != ""){
            this.requestInfo(value,1,10,this.state.sendStatus)
        }
    }

    // http request 请求,并更细数据
    requestInfo(orderId,pageNum,pageSize){
        Relay.Store.commitUpdate(
            new EnterpriseTaxRebateList({
                orderId:orderId,
                sendStatus:this.state.sendStatus,
                pageSize:pageSize,
                pageNum:pageNum
            }),{
                onFailure:(res)=>{},
                onSuccess:(res)=>{
                    const d = res.enterpriseTaxRebateList.enterpriseTaxRebateList;
                    if(d.errorCode != "0") {
                        if(d.errorCode == "500"){ message.error("服务器错误，请联系系统管理员") }else{
                            message.error("数据请求失败，请刷新页面重试");
                        }
                        return;
                    }
                    const c = JSON.parse(JSON.stringify(d));
                    let data = c.enterpriseTaxRebateDomainList;
                    // 过滤需要处理的数据
                    data.forEach((item,index)=>{
                        data[index].key = item.orderId;
                        // 改变状态显示
                       item.sendStatus === "1" ? data[index].sendStatus = "待寄送" : data[index].sendStatus = "已寄送";
                    });

                    this.setState({
                        data:c.enterpriseTaxRebateDomainList,
                        totalResult:c.totalResult
                    });
                }
            })
    }

    // 按钮点击
    handleBtn1Click(k){
        this.setState({
            searchValue:"",
            sendStatus:k
        },()=>{
            // 更新数据
            this.requestInfo("",this.state.curPageNum[this.state.sendStatus-1],10);
        });
    }

    //  操作触发弹窗
    operation(sendState,index){
        if(!sendState){ return; }

        // 通过ref给弹框组件赋值[data]
        this.refs.operationModal.setState({
            data:this.state.data[index]
        });

        this.refs.operationModal.setState({
            vis:true,
        });
    }


    handleSearchChange(e){
        this.setState({
            searchValue:e.target.value
        })
    }

    filterOrderDetil(oty,oid){
        switch (oty){
            case 0:
                return;
            case 1:
                hashHistory.push('/orderdetailgms/'+oid);
                // hashHistory.push({pathname:'/orderdetailgms/',state:{'oid':oid}})
                return;
            case 2:
                hashHistory.push('/orderdetailraw/'+oid);
                // hashHistory.push({pathname:'/orderdetailraw/',state:{'oid':oid}})
                return;
            case 3:
                hashHistory.push('/orderdetailcloth/'+oid);
                // hashHistory.push({pathname:'/orderdetailcloth/',state:{'oid':oid}})
                return;
            case 4:
                hashHistory.push('/orderdetailprint/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;
            case 5:
                hashHistory.push('/orderdetailyarn/'+oid);
                // hashHistory.push({pathname:'/orderdetailprint/',state:{'oid':oid}})
                return;
        }
    }

    // 跳转到订单详情
    jumpOrderDeatil(t,r,i){
        if(!t){ return; }
        this.filterOrderDetil(parseInt(r.orderType,10),t);
    }

    heaBtnConfig = {
        className:"invoiceManage_left",
        btn1:{name:"待寄送", onClick:(e)=>{this.handleBtn1Click(1)},style:{marginRight:15}},
        btn2:{name:"已寄送", onClick:(e)=>{this.handleBtn1Click(2)}},
    };

    heaSearchConfig = {
        placeholder:"请输入订单编号",
        style:{width: 200,boxSizing:"border-box"}
    };

    // table header
    columns = [
        { title: '订单编号', dataIndex: 'orderId', key: 'orderId',render:(t,r,i)=>{
            return <a onClick={()=>this.jumpOrderDeatil(t,r,i)}> {t} </a>
        }},
        { title: '合同号', dataIndex: 'contract', key: 'contract'},

        { title: '贸易商', dataIndex: 'partyAEnName', key: 'partyAEnName'},

        { title: '实际订单金额', dataIndex: 'orderAmount', key: 'orderAmount'},

        { title: '发票金额', dataIndex: 'invoiceMoney', key: 'invoiceMoney'},
        { title: '退税金额', dataIndex: 'rebateMoney', key: 'rebateMoney'},
        { title: '状态', dataIndex: 'sendStatus', key: 'sendStatus'},

        { title: '操作人', dataIndex: 'sendUserName', key: 'sendUserName'},
        { title: '操作', dataIndex: 'operation', key: 'operation',render:(text,recode,index)=>
            // 点击操作，发送当前点击的寄送状态以及data的index
            <a onClick={()=>{this.operation(this.state.sendStatus,index)}}>
                {
                    this.state.sendStatus == "1" ? "寄送发票" : "查看发票"
                }
            </a>
        },
    ];

    //分页
    paginationChange(page,pageSize){
        // 为当前的寄送状态(已寄送/待寄送)更新当前的页数.（每一项都保留一份页数的状态）;
        this.state.curPageNum[this.state.sendStatus-1] = page;
        this.setState({
            curPageNum:this.state.curPageNum
        },()=>{
            this.requestInfo("",page,pageSize,this.state.sendStatus);
        });
    }

    render() {
        const{ sendStatus,data,searchValue,totalResult,curPageNum} = this.state;

        return(
            <div className="rebatemanage">
                <header>
                    <h3 className="rebatemanage_title"> 状态： </h3>
                    <HeaderLeft
                        key="header_left"
                        {...this.heaBtnConfig}
                        active={sendStatus}
                    />
                    <HeaderRight
                        key="header_right"
                        className="invoiceManage_right"
                        searchConf={this.heaSearchConfig}
                        onSearch={this.handleHeaSearch}
                        onChange={this.handleSearchChange}
                        value={searchValue}
                    />
                </header>

                <section>
                    <TableDetail
                        columns = {this.columns}
                        data={data}
                        paginationChange={this.paginationChange}
                        total={totalResult}
                        current={curPageNum[sendStatus-1]}
                    />
                </section>

                <OperModal
                    key="orderModal"
                    status={sendStatus}
                    ref="operationModal"
                    requestInfo={this.paginationChange}
                />
            </div>
        )
    }

}